'use strict';

module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const CommentsSchema = new Schema({
    // 评论人头像
    icon: { type: String, default: '', max: 200 },
    // 评论人ID
    userId: { type: String, default: '', max: 50 },
    // 评论人名称
    name: { type: String, default: '', max: 20 },
    // 提及人（在子评论里面的评论）
    mention: { type: String, default: '', max: 20 },
    // 子对象
    children: [{ type: Schema.Types.ObjectId, ref: 'Comments' }],
    // 评论内容
    content: { type: String, default: '', max: 400 },
    // 评论时间
    date: { type: Date, default: new Date() },
  });

  /**
   * 添加评论
   */
  CommentsSchema.statics.addComments = async function(id, commentsId) {
    return this.updateOne({
      _id: mongoose.Types.ObjectId(id),
    }, {
      $push: {
        children: mongoose.Types.ObjectId(commentsId),
      },
    });
  };

  // 获取单个数据
  CommentsSchema.statics.findWithId = function(id) {
    return this.findOne({
      _id: mongoose.Types.ObjectId(id),
    });
  };

  // 删除评论
  CommentsSchema.statics.removeSubComments = function(id, subCommentsId){
    return this.updateOne({
      _id: mongoose.Types.ObjectId(id),
    }, {
      $pull: {
        commentsList: {
          _id: mongoose.Types.ObjectId(subCommentsId),
        }
      }
    })
  }

  // 删除单个数据
  CommentsSchema.statics.deleteWithId = function(id){
    return this.deleteOne({
      _id: mongoose.Types.ObjectId(id),
    });
  }

  return mongoose.model('Comments', CommentsSchema, 'comments');
};
